#include "mw.h"
#include "./ui_mw.h"
#include <QDebug>
#include "serial_config.h"
#include "serial_config_type.h"
#include "thr_set.h"
#include <QTimer>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonParseError>
QSerialPort serial;


float s_env_t_thr_min;
float s_env_t_thr_max;
float s_env_h_thr_min;
float s_env_h_thr_max;
float s_check_t_thr_min;
float s_check_t_thr_max;
int s_co2_thr_max;

mw::mw(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::mw)
{
    ui->setupUi(this);
    recvTimeoutTimer = new QTimer(this);
    recvTimeoutTimer->setInterval(300);  // 100ms 超时
    recvTimeoutTimer->setSingleShot(true);  // 只触发一次
    connect(&serial, &QSerialPort::readyRead, this, &mw::serial_port_data_recv);
    connect(recvTimeoutTimer, &QTimer::timeout, this, &mw::serial_data_timeout);
    connect(ui->serial_config, &QPushButton::clicked, this, &mw::serial_config_btn_click);
    connect(ui->open_serial, &QPushButton::clicked, this, &mw::open_serial_btn_click);
    connect(ui->thr_set, &QPushButton::clicked,  this, &mw::thr_set_btn_click);
    ui->thr_set->setDisabled(true);
}

mw::~mw()
{
    delete ui;
}
void mw::serial_config_btn_click()
{
    serial_config config(this);
    connect(&config, &serial_config::serial_port_selected, this, &mw::serial_portname_recv);
    config.exec();
}

void mw::thr_set_btn_click()
{
    qDebug()<<"thr_set_btn_click";
    thr_set thr_set1(this);

    thr_set1.exec();
}
void mw::open_serial_btn_click()
{
    if (serial.isOpen()) {
        // 串口已打开，关闭串口
        serial.close();
        QMessageBox::information(this, "提示", "串口已关闭！");
        ui->open_serial->setText("打开串口");
        ui->thr_set->setDisabled(true);
        return;
    }

    // 串口未打开，尝试打开
    if(!serial_config_struct.portName.isEmpty())
    {
        serial.setPortName(serial_config_struct.portName);

        // 设置参数
        serial.setBaudRate(serial_config_struct.baudRate);
        serial.setParity(serial_config_struct.parity);
        serial.setDataBits(serial_config_struct.dataBits);
        serial.setStopBits(serial_config_struct.stopBits);
        serial.setFlowControl(QSerialPort::NoFlowControl);

        // 尝试打开串口
        if (serial.open(QIODevice::ReadWrite)) {
            QMessageBox::information(this, "提示", "串口打开成功！");
            ui->open_serial->setText("关闭串口");
            ui->port_label->setText(serial.portName());
            ui->thr_set->setDisabled(false);
        } else {
            QMessageBox::warning(this, "错误", "串口打开失败！\n" + serial.errorString());
            ui->port_label->setText("");
            ui->thr_set->setDisabled(true);
        }
    } else {
        QMessageBox::warning(this, "警告", "请先配置串口！");
    }
}

void mw::serial_portname_recv(const QString &port_name)
{
    qDebug() << "接收到串口号:" << port_name;
    ui->port_label->setText(port_name);
}

void mw::serial_port_data_recv()
{
    QByteArray data = serial.readAll();
    serialBuffer.append(data);
    recvTimeoutTimer->start();
}

void mw::serial_data_timeout()
{
    if (serialBuffer.isEmpty()) return;

    qDebug() << "100ms超时，处理一帧原始数据：" << serialBuffer;

    // 正则提取 JSON 数据
    static const QRegularExpression re(R"(\{[^{}]*\})");
    QRegularExpressionMatch match = re.match(serialBuffer);
    if (!match.hasMatch()) {
        qDebug() << "未找到有效的 JSON 数据";
        serialBuffer.clear();
        return;
    }

    QByteArray jsonPart = match.captured(0).toUtf8();

    // 尝试解析 JSON
    QJsonParseError error;
    QJsonDocument doc = QJsonDocument::fromJson(jsonPart, &error);
    if (error.error != QJsonParseError::NoError || !doc.isObject()) {
        qDebug() << "JSON 解析失败：" << error.errorString();
        serialBuffer.clear();
        return;
    }

    QJsonObject obj = doc.object();

    // 解析数据
    double gy906_temp = obj.value("ot").toDouble();
    double dht_temp = obj.value("t").toDouble();
    double dht11_humi = obj.value("h").toDouble();
    int co2 = obj.value("c").toInt();

    float env_t_thr_min = obj.value("ett-").toDouble();
    float env_t_thr_max = obj.value("ett+").toDouble();
    float env_h_thr_min = obj.value("eht-").toDouble();
    float env_h_thr_max = obj.value("eht+").toDouble();
    float check_t_thr_min = obj.value("ctt-").toDouble();
    float check_t_thr_max = obj.value("ctt+").toDouble();
    int co2_thr_max = obj.value("cot+").toInt();

    bool have_people = obj.value("p").toInt();
    bool co2_alarm = obj.value("ca").toInt();
    bool env_t_min_alarm = obj.value("et-a").toInt();
    bool env_t_max_alarm = obj.value("et+a").toInt();
    bool env_h_min_alarm = obj.value("eh-a").toInt();
    bool env_h_max_alarm = obj.value("eh+a").toInt();
    bool alarm_flag = obj.value("af").toInt();

    s_env_t_thr_min = env_t_thr_min;
    s_env_t_thr_max = env_t_thr_max;
    s_env_h_thr_min = env_h_thr_min;
    s_env_h_thr_max = env_h_thr_max;
    s_check_t_thr_min = check_t_thr_min;
    s_check_t_thr_max = check_t_thr_max;
    s_co2_thr_max = co2_thr_max;

    // 输出调试信息
    qDebug() << "环境温度阈值:" << QString::number(env_t_thr_min, 'f', 2) << "~" << QString::number(env_t_thr_max, 'f', 2);
    qDebug() << "环境湿度阈值:" << QString::number(env_h_thr_min, 'f', 2) << "~" << QString::number(env_h_thr_max, 'f', 2);
    qDebug() << "人体温度阈值:" << QString::number(check_t_thr_min, 'f', 2) << "~" << QString::number(check_t_thr_max, 'f', 2);
    qDebug() << "CO2最大阈值:" << co2_thr_max;
    qDebug() << "报警标志:";
    qDebug() << "CO2报警:" << co2_alarm;
    qDebug() << "环境温度低报警:" << env_t_min_alarm;
    qDebug() << "环境温度高报警:" << env_t_max_alarm;
    qDebug() << "环境湿度低报警:" << env_h_min_alarm;
    qDebug() << "环境湿度高报警:" << env_h_max_alarm;
    qDebug() << "是否探测到人报警:" << have_people;
    qDebug() << "总报警标志:" << alarm_flag;

    // 更新数据显示（保留两位小数）
    ui->CHECK_T->setText(QString::number(gy906_temp, 'f', 2));
    ui->ENV_T_VAL->setText(QString::number(dht_temp, 'f', 2));
    ui->ENV_H_VAL->setText(QString::number(dht11_humi, 'f', 2));
    ui->CO2_PPM->setText(QString::number(co2));

    ui->check_t_thr_max->setText(QString::number(check_t_thr_max, 'f', 2));
    ui->check_t_thr_min->setText(QString::number(check_t_thr_min, 'f', 2));
    ui->co2_thr_max->setText(QString::number(co2_thr_max));
    ui->env_h_thr_max->setText(QString::number(env_h_thr_max, 'f', 2));
    ui->env_h_thr_min->setText(QString::number(env_h_thr_min, 'f', 2));
    ui->env_t_thr_max->setText(QString::number(env_t_thr_max, 'f', 2));
    ui->env_t_thr_min->setText(QString::number(env_t_thr_min, 'f', 2));

    // 报警显示逻辑
    ui->co2_alram_text->setText(co2_alarm ? "CO₂浓度过高" : "CO₂浓度正常");

    if (env_t_min_alarm)
        ui->env_t_alram_text->setText("环境温度过低");
    else if (env_t_max_alarm)
        ui->env_t_alram_text->setText("环境温度过高");
    else
        ui->env_t_alram_text->setText("环境温度正常");

    if (env_h_min_alarm)
        ui->env_h_alram_text->setText("环境湿度过低");
    else if (env_h_max_alarm)
        ui->env_h_alram_text->setText("环境湿度过高");
    else
        ui->env_h_alram_text->setText("环境湿度正常");

    ui->have_people_text->setText(have_people ? "已检测到人体" : "未检测到人体");

    // 清空缓存
    serialBuffer.clear();
}



